package org.alerve.android.resourcebuilder.modules;

import static java.lang.Character.isUpperCase;
import static java.lang.Character.toLowerCase;

import java.util.Map;

import org.alerve.android.resourcebuilder.ResourceNameParser;
import org.alerve.android.resourcebuilder.ResourceNameParser.IParser;
import org.alerve.utils.Cache;

/**
 * 
 * Default implementation of the {@link ResourceNameParser} which converts
 * camelCase into not "camel_case"
 * 
 * @author pabs87@gmail.com
 * 
 */
public class DefaultResourceNameParser implements IParser {

    private static final Map<String, String> stringCache = new Cache<String, String>();
    private static final char UNDERSCORE = '_';

    @Override
    public String parse(String name) {
        String result;
        if (stringCache.containsKey(name)) {
            result = stringCache.get(name);
        } else {
            char[] charName = name.toCharArray();
            StringBuilder builder = new StringBuilder(charName.length * 2);
            // lower-case the first letter in case is the name of a class
            if (isUpperCase(charName[0])) {
                charName[0] = toLowerCase(charName[0]);
            }
            // process the letters
            for (char c : charName) {
                if (isUpperCase(c)) {
                    c = toLowerCase(c);
                    builder.append(UNDERSCORE);
                }
                builder.append(c);
            }
            result = builder.toString();
            stringCache.put(name, result);
        }
        return result;
    }
}